package com.wave2.shadow.testJavaGolfAssocation;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import com.wave2.shadow.controller.JGAController;
import com.wave2.shadow.dao.RegistrationDao;
import com.wave2.shadow.model.JoinForm;
import com.wave2.shadow.persistence.Contacts;
import com.wave2.shadow.validator.JoinFormValidator;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
		"classpath:/com/wave2/shadow/testJavaGolfAssocation/context.xml",
		"classpath:/com/wave2/shadow/hsqldb/hsqldb-context.xml" })
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public class testJGAController {

	@Autowired
	private JGAController jgacontroller;

	@Autowired
	private RegistrationDao registrationDao;
	
	@Autowired
	private JoinFormValidator joinFormValidator;

	@Test
	public void testContextLoaded() {
		//TODO: insert a mockito mock for JGAController here?
		
		//Make sure the beans are autowired in.
		assertTrue(jgacontroller != null);
		assertTrue(registrationDao != null);
		assertTrue(joinFormValidator != null);
	}	
	
	@Test
	public void testProcessForm() {
		try {
			
			JoinForm myform = new JoinForm();
			myform.setEmail("richard.ashley@hcl.com");
			myform.setFirstName("richard");
			myform.setLastName("ashley");
			myform.setPassword("mypassword");
			myform.setPhonenumber("1-585-701-5906");

			BindingResultMock bresult = new BindingResultMock();

			Map<String, Object> testmodel = new HashMap<String, Object>();

			String jgaresult = jgacontroller.processForm(myform, bresult, testmodel);

			assertEquals("login", jgaresult);
			assertEquals(myform.getEmail(), testmodel.get("email"));

			List<Contacts> lst = registrationDao.getUser();

			// do assert
			assertTrue(lst != null && !lst.isEmpty());

			Contacts person = lst.get(1);
			assertEquals(person.getEmail(), myform.getEmail());
			assertEquals(person.getFirstname(), myform.getFirstName());
			assertEquals(person.getLastname(), myform.getLastName());
			assertEquals(person.getPass(), myform.getPassword());
			assertEquals(person.getPhone1(), myform.getPhonenumber());
			
		} catch (Exception e) {
			
			e.printStackTrace(System.err);			
			fail ("Unhandled Exception! See Console for the stack.");
			
		}

	}
}
